<template>
  <div style="height: inherit;overflow:hidden;">
    <el-divider />
    <div v-if="suffix === 'pdf'" style="height: 100%;">
      <iframe v-if="pdfContent.length > 0" :src="pdfContent" width="100%" height="100%" frameborder="0" />
    </div>
    <div v-else-if="suffix === 'txt'" style="height: 100%;overflow:auto;">
      <div v-if="txtContent.length > 0" v-html="txtContent" />
    </div>
    <div v-else-if="suffix === 'xls' || suffix === 'xlsx' " style="height: 100%;overflow:auto;">
      <el-table v-if="excelContent.header.length > 0" :data="excelContent.results" border highlight-current-row style="width: 100%">
        <el-table-column v-for="item in excelContent.header" :key="item + Math.random()" :prop="item" :label="item" />
      </el-table>
      <!--      <div v-if="excelContent.header.length > 0" v-html="excelContent.results" />-->
    </div>
    <div v-else-if="suffix === 'doc' || suffix === 'docx' " style="height: 100%;overflow:auto;">
      <div v-if="wordContent.length > 0" v-html="wordContent" />
    </div>
    <div v-else-if="suffix === 'pptx'" style="height: 100%;overflow:auto;" />
    <div v-else-if="suffix === 'zip' || suffix === 'rar'" style="height: 100%;overflow:auto;" />
    <div v-else-if="suffix === 'jpg' || suffix === 'png'" style="height: 100%;overflow:auto;">
      <img :src="imgUrl" alt="" width="100%">
    </div>
    <div v-else-if="suffix === 'mp4'" ref="mp4Wrapper" style="height: 100%;overflow:auto;">
      <video-player
        v-if="playerOptions.sources[0].src"
        ref="videoPlayer"
        class="video-player-box"
        :options="playerOptions"
        :playsinline="true"
        custom-event-name="customstatechangedeventname"
      />
    </div>
    <div v-else style="height: 100%;overflow:auto;" />
  </div>
</template>
<script>
import { downloadCommand } from '@/api/file'
import mammoth from 'mammoth'
import XLSX from 'xlsx'
import 'video.js/dist/video-js.css'
import { videoPlayer } from 'vue-video-player'
export default {
  name: 'PreviewPage',
  components: {
    videoPlayer
  },
  props: {
    row: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      suffix: '',
      txtContent: '',
      pdfContent: '',
      wordContent: '',
      excelContent: {
        header: [],
        results: []
      },
      imgUrl: '',
      videoUrl: '',
      playerOptions: {
        // videojs options
        width: '100%',
        muted: true,
        language: 'zh-CN',
        fluid: true,
        playbackRates: [0.7, 1.0, 1.5, 2.0],
        sources: [{
          type: 'video/mp4',
          src: ''
        }],
        poster: '/static/images/author.jpg'
      }
    }
  },
  watch: {
    row: {
      handler: function(val) {
        if (val) {
          this.txtContent = ''
          this.pdfContent = ''
          this.wordContent = ''
          this.excelContent = {
            header: [],
            results: []
          }
          const formData = {
            id: val.id,
            command: 'file'
          }
          this.getInfo(formData, val)
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    getInfo(formData, val) {
      const that = this
      downloadCommand(formData).then(response => {
        if (response) {
          this.suffix = val.fileExtension
          if (this.suffix === 'txt') {
            const that = this
            var reader = new FileReader()
            reader.readAsText(response)
            reader.onload = function(event) {
              that.txtContent = reader.result
            }
          } else if (this.suffix === 'pdf') {
            const blob = new Blob([response], { type: 'application/pdf' })
            const fileURL = URL.createObjectURL(blob)
            const url = encodeURIComponent(fileURL)
            this.pdfContent = `static/pdf/web/viewer.html?file=${url}`
          } else if (this.suffix === 'doc' || this.suffix === 'docx') {
            const that = this
            var file = response
            var reader1 = new FileReader()
            reader1.readAsArrayBuffer(file)
            reader1.onload = function(e) {
              const buffer = e.target.result
              mammoth.convertToHtml({ arrayBuffer: buffer }).then((result) => {
                that.wordContent = result.value
              }).done()
            }
          } else if (this.suffix === 'xls' || this.suffix === 'xlsx') {
            this.readerData(response)
          } else if (this.suffix === 'png' || this.suffix === 'jpg') {
            var file1 = response
            var reader2 = new FileReader()
            // 使用readAsArrayBuffer读取文件, result属性中将包含一个 ArrayBuffer 对象以表示所读取文件的数据
            reader2.readAsArrayBuffer(file1)
            reader2.onload = function(e) {
              const buffer = e.target.result
              const contentType = 'image/png'
              // 生成blob图片,需要参数(字节数组, 文件类型)
              const blob = new Blob([buffer], { type: contentType })
              // 使用 Blob 创建一个指向类型化数组的URL, URL.createObjectURL是new Blob文件的方法,可以生成一个普通的url,可以直接使用,比如用在img.src上
              that.imgUrl = window.URL.createObjectURL(blob)
            }
          } else if (this.suffix === 'mp4') {
            var file2 = response
            var reader3 = new FileReader()
            // 使用readAsArrayBuffer读取文件, result属性中将包含一个 ArrayBuffer 对象以表示所读取文件的数据
            reader3.readAsArrayBuffer(file2)
            reader3.onload = function(e) {
              const buffer = e.target.result
              const contentType = 'video/mp4'
              // 生成blob图片,需要参数(字节数组, 文件类型)
              const blob = new Blob([buffer], { type: contentType })
              // 使用 Blob 创建一个指向类型化数组的URL, URL.createObjectURL是new Blob文件的方法,可以生成一个普通的url,可以直接使用,比如用在img.src上
              that.playerOptions.sources[0].src = window.URL.createObjectURL(blob)
            }
          }
        }
      })
    },
    getHeaderRow(sheet) {
      const headers = []
      const range = XLSX.utils.decode_range(sheet['!ref'])
      let C
      const R = range.s.r
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
        /* find the cell in the first row */
        // let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
        let hdr = ' '
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
      }
      return headers
    },
    generateData({ header, results }) {
      this.excelContent.header = header
      this.excelContent.results = results
    },
    readerData(rawFile) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = e => {
          const data = e.target.result
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const header = this.getHeaderRow(worksheet)
          const results = XLSX.utils.sheet_to_json(worksheet, { defval: '' })
          this.generateData({ header, results })
          resolve()
        }
        reader.readAsArrayBuffer(rawFile)
      })
    }
  }
}
</script>
<style scoped lang="scss">
.el-divider--horizontal{
  margin: 5px 0 !important;
}
.video-player-box{
  width: 100%;
}
</style>

